package top.cn27.luckyhe.mirai.plugin.residence.command;

import kotlin.Unit;
import kotlin.coroutines.Continuation;
import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.command.CommandOwner;
import net.mamoe.mirai.console.command.CommandSender;
import net.mamoe.mirai.console.command.RawCommand;
import net.mamoe.mirai.console.permission.Permission;
import net.mamoe.mirai.contact.User;
import net.mamoe.mirai.message.data.MessageChain;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import top.cn27.luckyhe.mirai.plugin.residence.pojo.Player;
import top.cn27.luckyhe.mirai.plugin.residence.service.PlayerListService;
import top.cn27.luckyhe.mirai.plugin.residence.service.PlayerListServiceImpl;
import top.cn27.luckyhe.mirai.plugin.residence.utils.RconUtil;
import top.cn27.luckyhe.mirai.plugin.residence.utils.ResCommandHelp;
import top.cn27.luckyhe.mirai.plugin.residence.utils.ResListUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class ResCommand extends RawCommand {
    public ResCommand(@NotNull CommandOwner owner, @NotNull String primaryName, @NotNull String[] secondaryNames, @NotNull String usage, @NotNull String description, @NotNull Permission parentPermission, boolean prefixOptional) {
        super(owner, primaryName, secondaryNames, usage, description, parentPermission, prefixOptional);
    }

    @Nullable
    @Override
    public Object onCommand(@NotNull CommandSender commandSender, @NotNull MessageChain messageChain, @NotNull Continuation<? super Unit> continuation) {
        int mcLen = messageChain.toArray().length;
        String primaryName = getPrimaryName();
        String[] secondaryNames = getSecondaryNames();
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        if (mcLen == 0) {
            commandSender.sendMessage(ResCommandHelp.resHelpStr(primaryName, secondaryNames));
            return null;
        }

        String operation = messageChain.get(0).toString();

        switch (operation.toLowerCase()) {
            case "pset":
                onPSet(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(), 1, mcLen),
                        primaryName,
                        secondaryNames
                );
                break;
            case "set":
                onSet(
                        commandSender,
                        Arrays.copyOfRange(messageChain.toArray(), 1, mcLen),
                        primaryName,
                        secondaryNames
                );
                break;
            case "list":
                onList(commandSender, primaryName, secondaryNames);
                break;
            default:
                commandSender.sendMessage(operation + "这啥啊我看不懂，你要不看看" + commandPrefix + primaryName);
                return null;
        }

        return null;
    }

    private void onPSet(CommandSender commandSender, Object[] args, String primaryName, String[] secondaryNames) {
        if (args.length != 4) {
            commandSender.sendMessage("你特么是不是参数写少了啊，<领地名> <玩家名> <权限名> <true/false/remove>，四个呢");
            return;
        }
        String reqResName = args[0].toString();
        String reqResAddMcId = args[1].toString();
        String reqPerm = args[2].toString();
        String reqBool = args[3].toString();

        Player player = getPlayer(commandSender);
        if (player == null) {
            return;
        }

        String mcid = player.getMcId();

        String listResult = getListExecuteResult(commandSender);
        if (listResult == null) {
            return;
        }
        List<Map<String, String>> resMaps = ResListUtil.getSplitResult(listResult);

        boolean found = false;
        for (Map<String, String> map : resMaps) {
            if (map.get("name").equals(reqResName)) {
                if (!map.get("owner").equals(mcid)) {
                    commandSender.sendMessage("你有领地" + reqResName + "的权限，但领地不是你的，是" + map.get("owner") + "的，请找他发送指令");
                    return;
                } else {
                    found = true;
                }
            }
        }

        if (!found) {
            commandSender.sendMessage("特么你有个p的" + reqResName + "领地");
            return;
        }

        String command = "res pset " + reqResName + " " + reqResAddMcId + " " + reqPerm + " " + reqBool;

        String res;
        try {
            res = RconUtil.sendMcCommand(command);
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        commandSender.sendMessage("返回结果：\n" + res);
    }

    private void onSet(CommandSender commandSender, Object[] args, String primaryName, String[] secondaryNames) {
        if (args.length != 3) {
            commandSender.sendMessage("你特么是不是参数写错了啊，<领地名> <权限名> <true/false/remove>，三个呢");
            return;
        }
        String reqResName = args[0].toString();
        String reqPerm = args[1].toString();
        String reqBool = args[2].toString();

        Player player = getPlayer(commandSender);
        if (player == null) {
            return;
        }

        String mcid = player.getMcId();

        String listResult = getListExecuteResult(commandSender);
        if (listResult == null) {
            return;
        }
        List<Map<String, String>> resMaps = ResListUtil.getSplitResult(listResult);

        boolean found = false;
        for (Map<String, String> map : resMaps) {
            if (map.get("name").equals(reqResName)) {
                if (!map.get("owner").equals(mcid)) {
                    commandSender.sendMessage("你有领地" + reqResName + "的权限，但领地不是你的，是" + map.get("owner") + "的，请找他发送指令");
                    return;
                } else {
                    found = true;
                }
            }
        }

        if (!found) {
            commandSender.sendMessage("特么你有个p的" + reqResName + "领地");
            return;
        }

        String command = "res set " + reqResName + " " + reqPerm + " " + reqBool;

        String res;
        try {
            res = RconUtil.sendMcCommand(command);
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        commandSender.sendMessage("返回结果：\n" + res);
    }

    private Player getPlayer(CommandSender commandSender) {
        User user = commandSender.getUser();
        long qq = user == null ? 0 : user.getId();
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        PlayerListService service = new PlayerListServiceImpl();

        Player player;
        try {
            player = service.selectPlayerByQq(qq);
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return null;
        }

        if (player == null) {
            commandSender.sendMessage("你确定你绑定mcid了？\n使用" + commandPrefix + "mc setmcid 并按照指示完成绑定");
            return null;
        }

        return player;
    }

    private String getListExecuteResult(CommandSender commandSender) {

        Player player = getPlayer(commandSender);
        if (player == null) {
            return null;
        }

        String mcid = player.getMcId();
        String commandResult;
        try {
            commandResult = RconUtil.sendMcCommand("res list " + mcid);
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return null;
        }

        return commandResult;
    }

    private void onList(CommandSender commandSender, String primaryName, String[] secondaryNames) {

        String commandResult = getListExecuteResult(commandSender);
        if (commandResult == null) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        sb.append("看看你这穷B有几块地：\n");

        List<Map<String, String>> resMaps = ResListUtil.getSplitResult(commandResult);

        if (resMaps.size() == 0) {
            sb.append("哦，你没地啊");
            commandSender.sendMessage(sb.toString());
            return;
        }
        for (int i = 0; i < resMaps.size(); i++) {
            sb.append(i + 1).append(". ").append(resMaps.get(i).get("name")).append(" 地主：").append(resMaps.get(i).get("owner")).append("\n");
        }

        commandSender.sendMessage(sb.toString());
    }
}
